using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Library_management_system
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string userType = cmbUserType.SelectedItem?.ToString();
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            if (string.IsNullOrEmpty(userType) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入完整信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = "SELECT * FROM Users WHERE Username=@username AND Password=@password AND UserType=@usertype";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                cmd.Parameters.AddWithValue("@usertype", userType);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    this.Hide();
                    if (userType == "Admin")
                    {
                        MainForm mainForm = new MainForm(username);
                        mainForm.ShowDialog();
                    }
                    else
                    {
                        BorrowForm borrowForm = new BorrowForm(username);
                        borrowForm.ShowDialog();
                    }
                    this.Close();
                }
                else
                {
                    MessageBox.Show("用户名或密码错误！", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}